import Vue from 'vue';
import cookie from 'js-cookie';
import cookieKeys from '@const/cookie-keys';

// 统一状态码
const msgObj = {
  // '000000': '处理成功',//不需要通过异常方式提示
  // '100002': '数据解密失败',
  // '100003': '请求参数解析失败',
  // '999999': '系统异常',
  // '100004': '必填项未填',
  // '10000': '请求参数不能为空',
  // '100005': '备注信息不能超过200字',
  // '100006': '返回数据为空',
  '401': '登录失效，请重新登陆',
  // '402': '用户未登录，请登录',
  // '403': '鉴权异常，请联系管理员',
  // '404': '请求超时，请联系管理员',
  // '500': '系统异常，请联系管理员',
  // '200002': 'tenantId不能为空',
};

const path = process.env.COOKIE_PATH;
export default function axiosFunction (context) {
  // let { $axios, store, app, redirect } = context
  const { $axios, store } = context;

  $axios.onRequest(conf => {
    const config = conf
    let {url} = config;
    // let urlPath = config.url
    // jwt 验证
    if (store.state.token) {
      config.headers.common.Authorization = `Bearer ${store.state.token}`;
      config.headers.common.tenantId = `${store.state.tenantId}`;
    }

    url += url.indexOf('?') > -1 ? '&' : '?';
    // url += `tenantId=${store.state.tenantId}&userId=${
    //   store.state.userId
    // }&_=${new Date().getTime()}`
    url += `tenantId=${store.state.tenantId}&_=${new Date().getTime()}`;

    config.url = url;
    return config;
  });

  // CODE 不为0时的拦截
  $axios.onResponse(response => {
    const smsLogin = cookie.get('smsLogin')
    const apiUrl = response.config.url || ''
    const { data, config } = response;
    const hasBlobType = config.responseType === 'blob'
    const { code } = data;
    const newCode = window.parseInt(code);
    if (newCode !== 0 && !hasBlobType) {
      if (data.code === '401') {
        window.location.href = `${store.state.toNavPage}`;
      }
      if (data.code === 'SC1001') {
        Vue.$notify.error({
          title: '错误提示',
          message: msgObj[data.code] || `账号或密码输入错误${  data.msg  }次`,
          customClass: 'notifyZindex'
        })
      } else if (data.code === 'SC1002') {
        // code 1002首次登录，需重置密码
        store.commit('reSetPwd')
      } else if (window.location.hash === '#/basicData/channelBusinessManagement/add' && data.code === '100002') {
        Vue.$notify.error({
          title: '错误提示',
          message: data.msg,
          customClass: 'notifyZindex'
        })
      } else if (data.code === 'SC1005') {
        if (apiUrl.includes('loginByUserName')) {
          window.location.href = `${store.state.toNavPage  }login/bindPhone`
        } else {
          Vue.$notify.error({
            title: '错误提示',
            message: data.msg,
            customClass: 'notifyZindex'
          })
        }
      } else if (data.code === 'SC1003') {
          if (apiUrl.includes('loginByOpenPlatformCode')) {
            window.location.href = `${store.state.toNavPage  }login/wechatBindPhone`
          } else {
            Vue.$notify.error({
              title: '错误提示',
              message: data.msg,
              customClass: 'notifyZindex'
            })
          }
      } else if (data.code === 'SC1004') {
        if (apiUrl.includes('loginByPhone')) {
          if(smsLogin) {
            cookie.remove('smsLogin')
            window.location.href = `${store.state.toNavPage  }login/register`
          } else {
            window.location.href = `${store.state.toNavPage  }login/wechatLoginEndRegister`
          }
        } else {
          Vue.$notify.error({
            title: '错误提示',
            message: data.msg,
            customClass: 'notifyZindex'
          })
        }
      } else {
        Vue.$notify.error({
          title: '错误提示',
          message: msgObj[data.code] || data.msg || data.payload,
          customClass: 'notifyZindex'
        })
      }
      return Promise.reject(response);
    }
    return Promise.resolve(response);
  });

  $axios.onError(error => {
    if (process.client) {
      // axios 数据结构
      const resp = error.response || error;
      if (window.parseInt(resp.status) === 401) {
        cookieKeys.forEach(key => {
          cookie.remove(key, { path });
        });
        window.location.href = `${store.state.toNavPage  }?errorDese=http状态码返回401：`;
      }
    }
  });
}
